package au.com.somethingwritten.controller;

import au.com.somethingwritten.model.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class CartUpdateController extends HttpServlet {
	

	//handles adding a book to the cart.
	public void doPost( HttpServletRequest request,
						HttpServletResponse response)
						throws IOException, ServletException {
		
		try{
		//get the book id
		Integer bookId = Integer.parseInt((String)request.getParameter("book_id"));
		//get the quantity
		Integer quantity = Integer.parseInt(request.getParameter("quantity"));
		//minimum quantity to add it 1
		if(quantity == null)
			quantity = 1;
		
		//get the existing cart if it exists in the session.
		ShoppingCart tmpCart = (ShoppingCart)request.getSession().getAttribute("cart");
		if(tmpCart == null){
			//if it's null, create a new cart.
			tmpCart = new ShoppingCart();
			
		}
		
		//Create a book manager
		BookManager bookMan = new BookManager();
		//get the book to add to the cart
		Book tmpBook = bookMan.getBook(bookId);
		
		//add the book to the cart
		tmpCart.updateQuantity(tmpBook, quantity);
		
		
		//update the session's cart.
		request.getSession().setAttribute("cart", tmpCart);
		}catch(Exception e){
			//inputs were invalid. do nothing.
		}
		//forward data to the view
		RequestDispatcher view = request.getRequestDispatcher("cartPage.jsp");
		view.forward(request, response);
	}
	
	public void doGet( HttpServletRequest request,
			HttpServletResponse response)
			throws IOException, ServletException {
			//handle gets as posts.
			doPost(request, response); 
	}
}
